//
//  WJUserAccount.swift
//  WJWeibo
//
//  Created by Jie on 15/12/21.
//  Copyright © 2015年 周文杰. All rights reserved.
//

import UIKit

class WJUserAccount: NSObject, NSCoding{

    //MARK: - 属性
    ///AccessToken
    var access_token: String?
    ///当前授权用户的ID
    var uid: String?
    /// accesstoken的声明周期，秒
    var expires_in: NSTimeInterval = 0 {
        didSet {
            //自己生成，
            expires_Date = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    
    ///过期日期
    var expires_Date: NSDate?
    
    ///字典转模型
    init(dict: [String: AnyObject]) {
        super.init()

        setValuesForKeysWithDictionary(dict)
    }
    
    ///找不到属性赋值的时候就会调用该方法
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        
    }
    
    ///打印对象内容
    override var description: String {
        get {
            return "access_token: \(access_token), uid: \(uid), expires_in: \(expires_in), expires_Date: \(expires_Date)"
        }
    }
    
    //MARK: - 归档和解档
    ///归档
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeDouble(expires_in, forKey: "expires_in")
        aCoder.encodeObject(expires_Date, forKey: "expires_Date")
    }
    
    ///解档
    required init?(coder aDecoder: NSCoder) {
        //记得要给属性赋值
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        uid = aDecoder.decodeObjectForKey("uid") as? String
        expires_in = aDecoder.decodeDoubleForKey("expires_in")
        expires_Date = aDecoder.decodeObjectForKey("expires_Date") as? NSDate
        
    }
    
    ///沙盒路径
    static let path = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("userAccount.plist")
    
    
    
    ///保存账户用户信息
    func saveUserAccount() {
        //对象方法访问静态属性 需要加类名
        NSKeyedArchiver.archiveRootObject(self, toFile: WJUserAccount.path)
    }
    
    
    ///加载用户信息
    //用户信息不一定存在
    class func loadUserAccount() -> WJUserAccount? {
        if let userAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(WJUserAccount.path) as? WJUserAccount {
            
            if (userAccount.expires_Date?.compare(NSDate())) == NSComparisonResult.OrderedDescending{
                //没有过期
                print("加载到可用账号")
                return userAccount
                
            }else {
                print("账号过期")
                return nil
            }
            
        }else {
            print("没有加载到账号")
        }
        return nil
    }
    
    
}
